package com.dyna.auth.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dyna.api.domain.entity.SystemOath2Client;
import com.dyna.auth.mapper.Oath2ClientMapper;
import com.dyna.auth.service.Oath2ClientService;
import com.dyna.core.exception.CustomException;
import com.dyna.core.utils.StringUtil;
import com.dyna.enums.CommonStatusEnum;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * @author zhoucaiwang
 * @date 2023/8/15
 */

@Service
public class Oath2ClientServiceImpl
        extends ServiceImpl<Oath2ClientMapper, SystemOath2Client>
        implements Oath2ClientService {

    @Override
    public SystemOath2Client validOAuthClientFromCache(String clientId, String clientSecret, String authorizedGrantType,
                                                       Collection<String> scopes, String redirectUri) {
        // 校验客户端存在、且开启
        LambdaQueryWrapper<SystemOath2Client> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemOath2Client::getClientId, clientId);
        SystemOath2Client client = baseMapper.selectOne(queryWrapper);
        if (client == null) {
            throw new CustomException("OAuth2 客户端不存在");
        }
        if (CommonStatusEnum.isDisable(client.getStatus())) {
            throw new CustomException("OAuth2 客户端已禁用");
        }

        // 校验客户端密钥
        if (StrUtil.isNotEmpty(clientSecret) && ObjectUtil.notEqual(client.getSecret(), clientSecret)) {
            throw new CustomException("无效 client_secret");
        }
        // 校验授权方式
        if (StrUtil.isNotEmpty(authorizedGrantType) && !CollUtil.contains(client.getAuthorizedGrantTypes(), authorizedGrantType)) {
            throw new CustomException("不支持该授权类型");
        }
        // 校验授权范围
        if (CollUtil.isNotEmpty(scopes) && !CollUtil.containsAll(client.getScopes(), scopes)) {
            throw new CustomException("授权范围过大");
        }
        // 校验回调地址
        if (StrUtil.isNotEmpty(redirectUri) && !StringUtil.startWithAny(redirectUri, client.getRedirectUris())) {
            throw new CustomException("无效 client_secret");
        }
        return client;
    }


}
